<?php
/**
 * cms首页
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */

use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');
class indexControl extends mobileHomeControl{

    public function __construct() {
        parent::__construct();
    }

    /**
     * 首页
     */
    public function indexOp() {
        $model_mb_special = Model('mb_special');
        $data = $model_mb_special->getMbSpecialIndex();

        //手机端“我的视频” wap端不显示
        if (C('video_isuse') == 1) {
            $model_setting = Model('setting');
            $model_video_category = Model('mb_video_cate');
            $cate_list = $model_video_category->getVideoCategoryList(array('is_recommend' => 1));
            if(!empty($cate_list) && is_array($cate_list)) {
                $list_setting = $model_setting->getListSetting();
                $video_data = array();
                $video_list['video_isuse'] = C('video_isuse');
                $video_list['wap_display'] = 0;
                $video_list['video_modules_name'] = $list_setting['video_modules_name'];
                $video_list['video_modules_logo'] = UPLOAD_SITE_URL . DS . ATTACH_COMMON . DS . $list_setting['video_modules_logo'];
                //视频分类 显示推荐的分类
                foreach ($cate_list as $k => $v) {
                    $cate_list[$k]['cate_image'] = getMbVideoCateImageUrl($v['cate_image']);
                }
                $video_data['video_list'] = $video_list;
                $video_data['video_list']['item'] = $cate_list;
                array_push($data, $video_data);
            }
        }
        $this->_output_special($data, $_GET['type']);
    }

    /**
     * 专题
     */
    public function specialOp() {
        $model_mb_special = Model('mb_special');
        $info = $model_mb_special->getMbSpecialInfoByID($_GET['special_id']);
        $list = $model_mb_special->getMbSpecialItemUsableListByID($_GET['special_id']);
        $data = array_merge($info, array('list' => $list));
        $this->_output_special($data, $_GET['type'], $_GET['special_id']);
    }

    /**
     * 输出专题
     */
    private function _output_special($data, $type = 'json', $special_id = 0) {
        $model_special = Model('mb_special');
        if($_GET['type'] == 'html') {
            $html_path = $model_special->getMbSpecialHtmlPath($special_id);
            if(!is_file($html_path)) {
                ob_start();
                Tpl::output('list', $data);
                Tpl::showpage('mb_special');
                file_put_contents($html_path, ob_get_clean());
            }
            header('Location: ' . $model_special->getMbSpecialHtmlUrl($special_id));
            die;
        } else {
            output_data($data);
        }
    }

    /**
     * android客户端版本号
     */
    public function apk_versionOp() {
        $version = C('mobile_apk_version');
        $url = C('mobile_apk');
        if(empty($version)) {
           $version = '';
        }
        if(empty($url)) {
            $url = '';
        }

        output_data(array('version' => $version, 'url' => $url));
    }

    /**
     * 默认搜索词列表
     */
    public function search_key_listOp() {
        $list = @explode(',',C('hot_search'));
        if (!$list || !is_array($list)) { 
            $list = array();
        }
        if ($_COOKIE['hisSearch'] != '') {
            $his_search_list = explode('~', $_COOKIE['hisSearch']);
        }
        if (!$his_search_list || !is_array($his_search_list)) {
            $his_search_list = array();
        }
        output_data(array('list'=>$list,'his_list'=>$his_search_list));
    }

    /**
     * 热门搜索列表
     */
    public function search_hot_infoOp() {
        if (C('rec_search') != '') {
            $rec_search_list = @unserialize(C('rec_search'));
        }
        $rec_search_list = is_array($rec_search_list) ? $rec_search_list : array();
        $result = $rec_search_list[array_rand($rec_search_list)];
        output_data(array('hot_info'=>$result ? $result : array()));
    }

    /**
     * 高级搜索
     */
    public function search_advOp() {
        $area_list = Model('area')->getAreaList(array('area_deep'=>1),'area_id,area_name');
        if (C('contract_allow') == 1) {
            $contract_list = Model('contract')->getContractItemByCache();
            $_tmp = array();$i = 0;
            foreach ($contract_list as $k => $v) {
                $_tmp[$i]['id'] = $v['cti_id'];
                $_tmp[$i]['name'] = $v['cti_name'];
                $i++;
            }
        }

        //处理商品筛选项
        //默认分类，从而显示相应的属性和品牌
        $default_classid = intval($_GET['gc_id']);
        $_GET['cate_id'] = $default_classid;
        $model_search = Model('search');

        // 获取当前的分类内容
        $class_array = $this->_get_class_option_list($default_classid);

        //获得经过属性过滤的商品信息
        list($goods_param, $brand_array, $initial_array, $attr_array, $checked_brand, $checked_attr) = $model_search->getAttr($_GET, $default_classid);

        output_data(array('area_list'=>$area_list ? $area_list : array(),'contract_list'=>$_tmp ? $_tmp : array(),'brand_list'=>$brand_array,'initial_list'=>$initial_array,'attr_list'=>$attr_array,'checked_brand'=>$checked_brand,'checked_attr'=>$checked_attr,'class_list'=>$class_array));
    }

    private function _get_class_option_list($gc_id){
        $class_array = array();
        $class_array['top_class'] = array();
        $class_array['child_class'] = array();
        $class_array['checked_class'] = array();
        //所有分类
        $all_carr = Model('goods_class')->get_all_category();
        foreach ((array)$all_carr as $class_1){
            if(is_array($class_1['class2']) && !empty($class_1['class2'])){
                $class_2 = $class_1['class2'];
                foreach ($class_2 as $c2_list){
                    $_top_tmp = array();
                    $_top_tmp['gc_id'] = $c2_list['gc_id'];
                    $_top_tmp['gc_name'] = $c2_list['gc_name'];
                    $_top_tmp['type_id'] = $c2_list['type_id'];
                    if($c2_list['gc_id'] == $gc_id){
                        $class_array['checked_class']['gc_id'] = $c2_list['gc_id'];
                        $class_array['checked_class']['gc_name'] = $c2_list['gc_name'];
                        $class_array['checked_class']['top'] = $c2_list['gc_id'];
                    }
                    if(is_array($c2_list['class3']) && !empty($c2_list['class3'])){
                        $class_3 = $c2_list['class3'];
                        foreach ($class_3 as $cla_v){
                            $_child_tmp = array();
                            $_child_tmp['gc_id'] = $cla_v['gc_id'];
                            $_child_tmp['gc_name'] = $cla_v['gc_name'];
                            $_child_tmp['gc_parent_id'] = $cla_v['gc_parent_id'];
                            $_child_tmp['type_id'] = $cla_v['type_id'];
                            $class_array['child_class'][$c2_list['gc_id']][] = $_child_tmp;
                            if($cla_v['gc_id'] == $gc_id){
                                $class_array['checked_class']['gc_id'] = $cla_v['gc_id'];
                                $class_array['checked_class']['gc_name'] = $cla_v['gc_name'];
                                $class_array['checked_class']['top'] = $cla_v['gc_parent_id'];
                            }
                        }
                    }
                    $class_array['top_class'][] = $_top_tmp;
                }

            }
        }
        return $class_array;
    }

    /**
     * 得到红包列表
     * @return json
     */
    public function get_redpacket_listsOp()
    {
        $model_redpacket = Model('redpacket');
        $redpacket_list = $model_redpacket->getRedpacketLists($_GET);
        output_data($redpacket_list);
    }

    /**
     * 得到新人红包列表
     * @author maolvxiansheng
     * @return json
     */
    public function get_newbie_redpacket_listsOp()
    {
        $model_redpacket = Model('redpacket');
        $newbie_redpacket_list = $model_redpacket->newbieRedpacketLists('applet');
        output_data($newbie_redpacket_list);
    }
    /**
     *查询谁领取了该模板红包
     *
    */
    public function get_share_person_listOp()
    {
        $parameter = $_GET;
        $rpacket_t_id = isset($parameter['rpacket_t_id']) ? (int)$parameter['rpacket_t_id'] : 0;    //红包模板id
        $model_redpacket = Model('redpacket');
        $result = $model_redpacket->getDrawRedpacketUser($rpacket_t_id);
        output_data($result);
    }
    /**
     * 获取分享红包数据
     * @return json
     */
    public function get_share_redpacket_infoOp()
    {
        $parameter = $_GET;
        //是否登陆，若登陆查询是否具有领取权限
//        $member_id =  (int)$this->getMemberIdIfExists();
//        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        $member_id = 379;
        $if_inheritor = false;  //是否是点击他人分享链接
        $redpacket_share_person = isset($parameter['redpacket_share_person']) ? $parameter['redpacket_share_person'] : '';  //红包分享人
        $redpacket_share_secretkey = isset($parameter['redpacket_share_secretkey']) ? $parameter['redpacket_share_secretkey'] : '';    //红包分享比对密钥
        $rpacket_t_id = isset($parameter['rpacket_t_id']) ? (int)$parameter['rpacket_t_id'] : 0;    //红包模板id
        
        $model_redpacket = Model('redpacket');

        //点击他人分享的链接
        if ($redpacket_share_person && $redpacket_share_secretkey) {
            $decrypt_parameter = $model_redpacket->decryptParameter($redpacket_share_person, $redpacket_share_secretkey, $rpacket_t_id);
            $redpacket_share_person =  (is_array($decrypt_parameter) && isset($decrypt_parameter['member_id'])) ? (int)$decrypt_parameter['member_id'] : 0;
            if ($redpacket_share_person) $if_inheritor = true;
        }

        //查询可用红包模板
        $where = array();
        $where['rpacket_t_id']          = $rpacket_t_id;
        $where['rpacket_t_type']        = $model_redpacket::RPACKET_TYPE_SHARE;
        $where['rpacket_t_state']       = $model_redpacket::RPACKET_STATE_USABLE;
        $where['rpacket_t_start_date']  = array('elt', TIMESTAMP);
        $where['rpacket_t_end_date']    = array('egt', TIMESTAMP);
        $redpacket_template = $model_redpacket->getRptTemplateInfo($where);
        if (empty($redpacket_template)) {
            output_error('不存在该分享红包');
        }

        //查询谁领取了该模板红包
        $extend_data['share_person_list'] = $model_redpacket->getDrawRedpacketUser($rpacket_t_id, ($if_inheritor ? $redpacket_share_person : 0));

        //如果是点击他人分享链接，查询分享人头像，姓名等
        if ($if_inheritor) {
            $extend_data['share_person_info'] = Model('member')->getMemberInfoByID($redpacket_share_person, 'member_id,member_name,member_truename,member_avatar');
            if (!empty($extend_data['share_person_info'])) {
                $extend_data['share_person_info']['member_avatar_url'] = getMemberAvatar($extend_data['share_person_info']['member_avatar']);
            }
            // 若不是点击，自己分享的红包
            if ($redpacket_share_person !== $member_id) {
                /*增加点击人领取红包 begin*/
                //验证是否可领取红包
                $data = $model_redpacket->getCanChangeTemplateInfo($rpacket_t_id, $member_id, $redpacket_share_secretkey);
                /*用秘钥判断该红包是否已经获取过，防止用户重复获取该红包*/
                $data['info']['redpacket_share_secretkey'] = $redpacket_share_secretkey;
                if ($data['state'] !== true) {
                     output_error($data['msg']);
                } else {  //可以领取红包
                    try {
                        $model_redpacket->beginTransaction();
                        //添加红包信息
                        $data = $model_redpacket->exchangeRedpacket($data['info'], $member_id, $this->member_info['member_name']);
                        if ($data['state'] !== true ) {
                            throw new Exception($data['msg']);
                        }
                        $model_redpacket->commit();
                    } catch (Exception $e) {
                        output_error($e->getMessage());
                    }
                    $result['redpacket_status'] = array('status'=>true,'msg'=>'可以领红包');
                }
                /*增加点击人领取红包 end*/
            }else{
                output_error('已领过该红包');
            }
        }
        $result['share_person_list'] = $extend_data['share_person_list'];
        $result['share_person_info'] = $extend_data['share_person_info'];
        $result['share_redpacket_info'] = $redpacket_template;
        output_data($result);
    }

    /**
     * 获取红包详情
     * @return json
     */
    public function get_free_redpacket_infoOp()
    {
        $parameter = $_GET;
        $rpacket_t_id = isset($parameter['rpacket_t_id']) ? (int)$parameter['rpacket_t_id'] : 0;    //红包模板id
        $model_redpacket = Model('redpacket');

        //查询可用红包模板
        $where = array();
        $where['rpacket_t_id']         = $rpacket_t_id;
        $where['rpacket_t_state']      = $model_redpacket::RPACKET_STATE_USABLE;
        $where['rpacket_t_start_date'] = array('elt', TIMESTAMP);
        $where['rpacket_t_end_date']   = array('egt', TIMESTAMP);
        // $where['rpacket_t_gettype']    = $model_redpacket::RPACKET_GET_FREE; //红包领取方式
        $redpacket_template = $model_redpacket->getRptTemplateInfo($where);
        if (empty($redpacket_template)) {
            output_error('不存在该红包');
        }

        //是否登陆，若登陆查询是否具有领取权限
        $member_id =  $this->getMemberIdIfExists();
        if ($member_id) {
            $receive_state = $model_redpacket->getCanChangeTemplateInfo($rpacket_t_id, $member_id);
            $redpacket_template['member_redpack_jurisdiction'] = (isset($receive_state['state']) && ($receive_state['state'] === true)) ? true : false; //堵路会员是否拥有领取期限 true-拥有期限/false-不存在期限
            $redpacket_template['member_redpack_msg'] = ($redpacket_template['member_redpack_jurisdiction'] === true) ? '可以领取' : (isset($redpacket_template['msg']) ? $redpacket_template['msg'] : '无权限领取');
        }

        output_data($redpacket_template);
    }

    /**
     * 得到热卖商品
     * @return json
     */
    public function get_hot_goodsOp()
    {
        $good_lists = array();
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 5;
        $model_goods = Model('goods');
        $map = array(   //不包括虚拟商品、F码商品、预售商品、预定商品,且促销类型为 0
            'goods_promotion_type' => 0,
            'is_virtual'           => 0,
            'is_fcode'             => 0,
            'is_presell'           => 0,
            'is_book'              => 0,
            'is_batch'             => 0
        );
        $field = 'goods_id,goods_name,store_id,store_name,goods_price,goods_image,goods_click,goods_salenum,goods_collect,evaluation_good_star';
        $good_lists = $model_goods->getGoodsOnlineList($map, $field, 0, 'goods_salenum DESC', $limit);
        array_walk($good_lists, function(&$item, $keys){
            $item['goods_image_url'] = cthumb($item['goods_image'], 360, $item['store_id']);
        });
        output_data($good_lists);
    }

}
